package com.specter.utils;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Note:Ajax调用工具类
 * 
 * @author Liang.Wang
 * @version 2010-11-23 下午03:05:36
 */
public class JSONUtils {
	private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";

	public static String bean2json(Object obj) {
		return bean2json(obj, DEFAULT_DATE_PATTERN);
	}

	public static String bean2json(Object obj, String dateFormat) {
		ObjectMapper mapper = new ObjectMapper();
		mapper.setDateFormat(new SimpleDateFormat(dateFormat));
		String json = null;
		try {
			json = mapper.writeValueAsString(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}

	public static String list2json(List<?> list) {
		return list2Json(list, DEFAULT_DATE_PATTERN);
	}

	public static String list2Json(List<?> list, String dateFormat) {
		ObjectMapper mapper = new ObjectMapper();
		mapper.setDateFormat(new SimpleDateFormat(dateFormat));
		String json = null;
		try {
			json = mapper.writeValueAsString(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}

	@SuppressWarnings("unchecked")
	public static Map<String, Object> json2bean(String json) {
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> map = null;
		try {
			map = mapper.readValue(json, java.util.LinkedHashMap.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	public static <T> T json2bean(String json, Class<T> clazz) {
		ObjectMapper mapper = new ObjectMapper();
		T t = null;
		try {
			t = mapper.readValue(json, clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}

}
